package com.tecklab.demo.oss;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

public class GoogleFileUtil {
    public static String uploadFile(String filePath, String fileName, String bucketName) throws IOException {

        //读取本地存储的服务账号的json密钥，拿到该服务账号的权限
        GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/Users/sun/Desktop/gcp/project-20230615-b133b1131e9e.json"));

        //创建服务账号对应的操作对象
        Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

        // 将本地指定路径的文件转换为字节
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));

        // 1、上传文件图片到指定的存储桶中
        BlobId blobId = BlobId.of(bucketName, fileName);
        System.out.println("blobId.getName():\t" + blobId.getName());
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
        Blob blob = storage.create(blobInfo, bytes);

        //修改已经上传的文件类型为 image/jpg
        blob.toBuilder().setContentType("image/png").build().update();

        // 2、生成Signed URL
        URL signedUrl = storage.signUrl(blobInfo, 7, TimeUnit.DAYS, Storage.SignUrlOption.withV4Signature());

        // 3、下载文件
        String destFilePath = "/Users/sun/Desktop/gcp2/2.png";
        blob = storage.get(BlobId.of(bucketName, fileName));
        File file = new File("/Users/sun/Desktop/gcp2/");
        file.mkdirs();
        blob.downloadTo(Paths.get(destFilePath));
        System.out.println(
                "Downloaded object "
                        + fileName
                        + " from bucket name "
                        + bucketName
                        + " to "
                        + destFilePath);

        return signedUrl.toString();

    }


    public static void main(String[] args) throws IOException {
        String filepath = uploadFile("/Users/sun/Desktop/gcp/1.png", "file/path/1.png", "im9002-image-bucket");
        System.out.println("公开访问地址是:\t" + filepath);
    }

}
